<template>
  <div class="app-container">
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/" class="breadcrumb">
      <el-breadcrumb-item><i class="el-icon-location"></i> 设置</el-breadcrumb-item>
      <el-breadcrumb-item>部门管理</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 操作按钮区 -->
    <div class="handle-btn">
      <el-button type="primary" icon="el-icon-plus" @click="handleAdd">新增</el-button>
    </div>

    <!-- 搜索区 -->
    <el-form :inline="true" class="search-form">
      <el-form-item>
        <el-input
          v-model="searchKey"
          placeholder="请输入部门名称搜索"
          clearable
          style="width: 200px;">
        </el-input>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 部门列表 -->
    <el-table
      :data="deptList"
      row-key="id"
      :tree-props="{ children: 'children', hasChildren: '!leaf' }"
      border
      style="width: 100%; margin-top: 15px;">
      <el-table-column
        prop="deptName"
        label="部门名称"
        width="200">
        <template slot-scope="scope">
          <!-- 处理嵌套缩进 -->
          <span :style="{ 'padding-left': (scope.row.level * 20) + 'px' }">
            {{ scope.row.deptName }}
          </span>
        </template>
      </el-table-column>

      <el-table-column
        prop="deptStatus"
        label="部门状态"
        width="120">
        <template slot-scope="scope">
          <el-tag :type="scope.row.deptStatus === '启用' ? 'success' : 'danger'">
            {{ scope.row.deptStatus === '启用' ? '启用' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column
        prop="createTime"
        label="创建时间"
        width="180">
      </el-table-column>

      <el-table-column
        prop="creator"
        label="创建人"
        width="120">
      </el-table-column>

      <el-table-column
        prop="remark"
        label="备注">
      </el-table-column>

      <el-table-column
        label="操作"
        width="250">
        <template slot-scope="scope">
          <el-button
            type="text"
            size="small"
            @click="handleAddChild(scope.row)">
            新建子部门
          </el-button>
          <el-button
            type="text"
            size="small"
            @click="handleEdit(scope.row)">
            编辑
          </el-button>
          <el-button
            type="text"
            size="small"
            text-danger
            @click="handleDelete(scope.row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        background
        :current-page="pagination.pageNum"
        :page-size="pagination.pageSize"
        :total="pagination.total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, prev, pager, next, sizes, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange">
      </el-pagination>
    </div>

    <!-- 新增/编辑部门弹窗 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="500px"
      :close-on-click-modal="false">
      <el-form
        ref="deptForm"
        :model="deptForm"
        :rules="deptRules"
        label-width="100px">
        <el-form-item label="上级部门" prop="parentId">
          <el-select
            v-model="deptForm.parentId"
            placeholder="请选择上级部门">
            <el-option
              v-for="dept in allDepts"
              :key="dept.id"
              :label="dept.deptName"
              :value="dept.id"
              :disabled="dept.id === deptForm.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="部门名称" prop="deptName">
          <el-input v-model="deptForm.deptName" placeholder="请输入部门名称"></el-input>
        </el-form-item>
        <el-form-item label="部门状态" prop="deptStatus">
          <el-radio-group v-model="deptForm.deptStatus">
            <el-radio label="启用">启用</el-radio>
            <el-radio label="禁用">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="deptForm.remark"
            type="textarea"
            rows="3"
            placeholder="请输入备注信息"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </div>
    </el-dialog>

    <!-- 删除确认弹窗 -->
    <el-dialog
      title="确认删除"
      :visible.sync="deleteDialogVisible"
      width="300px"
      :close-on-click-modal="false">
      <p>确定要删除该部门吗？删除后将无法恢复。</p>
      <div slot="footer">
        <el-button @click="deleteDialogVisible = false">取消</el-button>
        <el-button type="danger" @click="confirmDelete">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listDept, getDept, delDept, addDept, updateDept, getAllDept } from "@/api/tms/set/department";

export default {
  name: "DepartmentManagement",
  data() {
    return {
      // 部门列表数据
      deptList: [],
      // 所有部门（用于选择上级部门）
      allDepts: [],
      // 搜索条件
      dateRange: [],
      searchKey: "",
      // 分页参数
      pagination: {
        pageNum: 1,
        pageSize: 10,
        total: 0
      },
      // 弹窗状态
      dialogVisible: false,
      deleteDialogVisible: false,
      dialogTitle: "新增部门",
      // 当前操作的部门ID
      currentDeptId: null,
      // 表单数据
      deptForm: {
        id: null,
        parentId: 0,
        deptName: "",
        deptStatus: "启用",
        remark: ""
      },
      // 表单验证规则
      deptRules: {
        deptName: [
          {required: true, message: "请输入部门名称", trigger: "blur"},
          {min: 1, max: 30, message: "部门名称长度在 1 到 30 个字符", trigger: "blur"}
        ],
        parentId: [
          {required: true, message: "请选择上级部门", trigger: "change"}
        ]
      }
    };
  },
  created() {
    this.loadDeptList();
    this.loadAllDepts();
  },
  methods: {
    // 加载部门列表
    loadDeptList() {
      const params = {
        pageNum: this.pagination.pageNum,
        pageSize: this.pagination.pageSize,
        deptName: this.searchKey
      };

      listDept(params).then(response => {
        // 假设接口返回格式为 { data: [], total: 100 }
        const deptData = response.data || response;
        this.deptList = this.handleDeptData(deptData);
        // 从接口获取总条数，而不是使用当前页数据长度
        this.pagination.total = response.total || deptData.length;
      });
    },

    // 处理部门数据，构建树形结构
    handleDeptData(depts = []) {
      // 假设接口返回的是扁平数据，这里将其转换为树形结构
      const deptMap = {};
      const rootDepts = [];

      // 先构建部门映射
      depts.forEach(dept => {
        const deptId = Number(dept.id);
        deptMap[deptId] = {...dept, id: deptId, children: [], expanded: false, leaf: true, level: 0};
      });

      // 构建树形结构
      depts.forEach(dept => {
        const deptId = Number(dept.id);
        const current = deptMap[deptId];
        if (dept.parentId === null) {
          current.expanded = true;
          rootDepts.push(current);
        } else {
          const parentId = Number(dept.parentId);
          const parent = deptMap[parentId];
          if (parent) {
            parent.children.push(current);
            parent.leaf = false; // 有子部门的不是叶子节点
            current.level = parent.level + 1;
          } else {
            console.log('找不到父部门的子部门:', current.id, '父部门ID:', parentId);
            // 如果找不到父部门，将其作为根部门处理
            rootDepts.push(current);
          }
        }
      });

      console.log('处理后的部门树形结构:', rootDepts);
      return rootDepts;
    },

    // 加载所有部门（用于选择上级部门）
    loadAllDepts() {
      getAllDept().then(response => {
        this.allDepts = response.data || response;
      });
    },

    // 搜索
    handleSearch() {
      this.pagination.pageNum = 1;
      this.loadDeptList();
    },

    // 重置搜索
    resetSearch() {
      this.dateRange = [];
      this.searchKey = "";
      this.pagination.pageNum = 1;
      this.loadDeptList();
    },

    // 分页大小改变
    handleSizeChange(size) {
      this.pagination.pageSize = size;
      this.pagination.pageNum = 1;
      this.loadDeptList();
    },

    // 页码改变
    handleCurrentChange(page) {
      this.pagination.pageNum = page;
      this.loadDeptList();
    },

    // 新增部门
    handleAdd() {
      this.dialogTitle = "新增部门";
      this.deptForm = {
        id: null,
        parentId: 0,
        deptName: "",
        deptStatus: "启用",
        remark: ""
      };
      this.dialogVisible = true;
    },

    // 新增子部门
    handleAddChild(dept) {
      this.dialogTitle = "新增子部门";
      this.deptForm = {
        id: null,
        parentId: dept.id,
        deptName: "",
        deptStatus: "启用",
        remark: ""
      };
      this.dialogVisible = true;
    },

    // 编辑部门
    handleEdit(dept) {
      this.dialogTitle = "编辑部门";
      this.currentDeptId = dept.id;

      getDept(dept.id).then(response => {
        this.deptForm = {...(response.data || response)};
        this.dialogVisible = true;
      });
    },

    // 删除部门
    handleDelete(dept) {
      this.currentDeptId = dept.id;
      this.deleteDialogVisible = true;
    },

    // 确认删除
    confirmDelete() {
      delDept(this.currentDeptId).then(response => {
        this.$message.success("删除成功");
        this.deleteDialogVisible = false;
        this.loadDeptList();
      }).catch(error => {
        this.$message.error(error.msg || "删除失败");
      });
    },

    // 提交表单
    submitForm() {
      this.$refs.deptForm.validate(valid => {
        if (valid) {
          if (this.deptForm.id) {
            // 编辑
            updateDept(this.deptForm).then(response => {
              this.$message.success("更新成功");
              this.dialogVisible = false;
              this.loadDeptList();
            }).catch(error => {
              this.$message.error(error.msg || "更新失败");
            });
          } else {
            // 新增
            addDept(this.deptForm).then(response => {
              this.$message.success("新增成功");
              this.dialogVisible = false;
              this.loadDeptList();
            }).catch(error => {
              this.$message.error(error.msg || "新增失败");
            });
          }
        }
      });
    }
  }
};
</script>

<style scoped>
.breadcrumb {
  margin: 15px 0;
}

.handle-btn {
  margin-bottom: 15px;
}

.search-form {
  background: #f5f7fa;
  padding: 15px;
  border-radius: 4px;
}

.pagination-container {
  margin-top: 15px;
  text-align: right;
}
</style>
